<script setup>
import { ref, onMounted, watch } from "vue";
import { useRoute } from "vue-router";
import * as pdfjsLib from "pdfjs-dist";
import SendEmail from "../sendEmail";
import { ArrowRightBold, ArrowLeftBold } from "@element-plus/icons-vue";
import { copyToClipboard } from "../../utils";

pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
  "pdfjs-dist/build/pdf.worker.min.js",
  import.meta.url
).href;
const watermarkPoint = [
  [-120, -66],
  [-120, 66],
  [120, -66],
  [120, 66],
]; // 水印坐标
const watermarkText = "钱大妈"
const props = defineProps(["url", "height"]);
const route = useRoute();

const isShow = ref(false);
const heightValue = ref(props.height);
const value = ref("2024-04-11");
const options = [{ label: "2024-04-11", value: "2024-04-11" }];

const copyHtml =
  import.meta.env.VITE_CAS_URL + "/html/document" + decodeURI(route.path);

// div 高度
const scrollHeight = computed(() => {
  const height = Number(props.height) + 56;
  return `height: calc(100vh - ${height}px)`;
});

// 引入工作环境 重要

const pdfScale = ref(0.9); // 关键！如果清晰度不行，慢慢调整这个数值。
const numPages = ref(0); // pdf一共多少页
const nums = ref(1); // 循环加载的参数
const currentNum = ref(1); // 当前页数
const inpDisabled = ref(true); // pad文件没有加载完所有页数则禁用
const imgSrcList = ref([]); // 存储paf每一页

let pageHeight = null; // 每一页高度
let pdfWrap = null;
let isChangeCurrentNum = false;

// url为pdf链接
const loadingTask = pdfjsLib.getDocument(props.url);

// dom加载之后
onMounted(() => {
  pdfWrap = document.getElementById("pdf");
  togglePage(nums.value);
});

watch(
  () => nums.value,
  (num) => {
    if (num <= numPages.value) {
      togglePage(num);
    } else {
      inpDisabled.value = false;
    }
  }
);

async function togglePage(pageNumber = 1) {
  const scale = pdfScale.value
  let pageDiv = null;
  loadingTask.promise.then(
    async (pdf) => {
      
      numPages.value = pdf.numPages;

      const page = await pdf.getPage(pageNumber);
      const canvasId = "the-canvas" + pageNumber;
      const canvas = document.getElementById(canvasId);
      const context = canvas.getContext("2d");
      const dpr = window.devicePixelRatio || 1;
      const bsr =
        context.webkitBackingStorePixelRatio ||
        context.mozBackingStorePixelRatio ||
        context.msBackingStorePixelRatio ||
        context.oBackingStorePixelRatio ||
        context.backingStorePixelRatio ||
        1;
      const ratio = dpr / bsr;

      // 获取pdf尺寸
      const viewport = page.getViewport({ scale });
      const viewportWidth = viewport.width.toFixed(0);
      const viewportHeight = viewport.height.toFixed(0);
      canvas.width = viewportWidth * ratio;
      canvas.height = viewportHeight * ratio;
      canvas.style.width = viewportWidth + "px";
      canvas.style.height = viewportHeight + "px";
      context.scale(ratio, ratio);
      // context.setTransform(ratio, 0, 0, ratio, 0, 0);


      pageDiv = document.createElement("div");
      pageDiv.setAttribute(
        "style",
        `width: ${canvas.style.width}; position: relative; height: ${canvas.style.height}; margin-bottom: 4px;`
      );
      pageDiv.setAttribute("class", "canvas-div");
      pdfWrap.appendChild(pageDiv);
      pageDiv.appendChild(canvas);
      const pdfContainer = canvas.parentNode;
      // 只赋值一次
      !pageHeight && (pageHeight = (canvas.height + 4).toFixed(2));

      const renderContext = {
        canvasContext: context,
        viewport: viewport,
      };
      const renderTask = page.render(renderContext);
      const annotations = await page.getAnnotations();
      annotations.forEach((annotation) => {
        if (annotation.subtype === "Link" && annotation.url) {
          /**
           * x: rect[0] ---- rect[2]
           * 
           * y: rect[1]
           *    |
           *    |
           * y: rect[3]
           */
          const rect0 = annotation.rect[0];
          const rect2 = annotation.rect[2];
          const rect1 = annotation.rect[1];
          const rect3 = annotation.rect[3];

          const width = ((rect2 - rect0) * scale).toFixed(0);
          const height = ((rect3 - rect1) * scale).toFixed(0);
          const y = (viewportHeight - (rect1 * scale) - height).toFixed(0);
          const x = rect0 * scale; // 根据 scale 调整位置

          // 创建一个 HTML 元素代表链接区域
          const linkDiv = document.createElement("span");
          linkDiv.style.position = "absolute";
          linkDiv.style.left = `${x}px`;
          linkDiv.style.top = `${y}px`;
          linkDiv.style.width = `${width}px`;
          linkDiv.style.height = `${height}px`;
          linkDiv.style.borderRadius = "4px";
          linkDiv.style.backgroundColor = "rgba(0, 0, 255, 0.1)"; // 或者设置为你想要的样式
          linkDiv.style.cursor = "pointer"; // 鼠标悬停时变为手型图标
          linkDiv.style.zIndex = 1000; // 确保在最上层

          // 添加点击事件监听器
          linkDiv.addEventListener("click", (event) => {
            event.preventDefault();
            window.open(annotation.url, "_blank"); // 打开链接
          });

          // 将链接 div 添加到 canvas 的父元素中
          pdfContainer.appendChild(linkDiv);
        }
      });

      renderTask.promise.then(() => {
        // 添加水印
        context.font = `${16 / pdfScale.value}px Microsoft Yahei`;
        context.fillStyle = "rgba(0, 0, 0, 0.15)";
        context.textAlign = "center";
        context.textBaseline = "middle";
        // 设置自定义文本位于每一页pdf的空间位置
        watermarkPoint.forEach((point) => {
          context.translate(
            ((viewport.width * pdfScale.value) / 2 + point[0]) / pdfScale.value,
            ((viewport.height * pdfScale.value) / 2 + point[1]) / pdfScale.value
          );
          context.rotate((-30 * Math.PI) / 360);
          context.fillText(watermarkText, 0, 0);
        });
      })
      imgSrcList.value.push(canvas.toDataURL());
      // 完成 页码+1
      nums.value++;
    },
    function (reason) {
      console.error(reason);
    }
  );
}

function handleScroll(e) {
  if (!isChangeCurrentNum) {
    const current = e.target.scrollTop / pageHeight;
    currentNum.value = Math.ceil(current === 0 ? 1 : current);
  }
  isChangeCurrentNum = false;
}

function handleBeforePage() {
  currentNum.value = currentNum.value - 1 <= 0 ? 1 : currentNum.value - 1;
  goToPage(currentNum.value);
  isChangeCurrentNum = true;
}

function handleNextPage() {
  currentNum.value =
    currentNum.value + 1 >= numPages.value
      ? numPages.value
      : currentNum.value + 1;
  goToPage(currentNum.value);
  isChangeCurrentNum = true;
}

function goToPage(num) {
  pdfWrap.scrollTo(0, num === 1 ? 0 : pageHeight * num - pageHeight);
  currentNum.value = num;
  isChangeCurrentNum = true;
}

// 实现手势缩放
var pdfDev = window.document;
var lastTouchDistance = null;
pdfDev.addEventListener('touchstart', function(e) {
  if (e.targetTouches.length == 2) {
    lastTouchDistance = getTouchDistance(e.targetTouches);
  }
});
pdfDev.addEventListener('touchmove', function(e) {
  if (e.targetTouches.length == 2) {
    var touchDistance = getTouchDistance(e.targetTouches);
    var delta = touchDistance - lastTouchDistance;
    lastTouchDistance = touchDistance;
    pdfScale.value += delta / 100;
    // 设置缩放
    pdfDev.style.transform = 'scale(' + pdfScale.value + ')';
  }
});
pdfDev.addEventListener('touchend', function(e) {
  lastTouchDistance = null;
});
function getTouchDistance(touches) {
  var dx = touches[1].pageX - touches[0].pageX;
  var dy = touches[1].pageY - touches[0].pageY;
  return Math.sqrt(dx * dx + dy * dy);
}

</script>

<template>
  <div>
    <div class="home-top" v-if="heightValue >= 40">
      <div class="left">
        版本日期
        <el-select
          v-model="value"
          placeholder="版本日期"
          style="width: 120px; margin-left: 10px"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="f">
        <div class="btn" @click="copyToClipboard(copyHtml)">复制地址</div>
        <div class="btn" @click="isShow = true">下载</div>
      </div>
    </div>
    <div
      class="overflow-y-scroll"
      id="pdf"
      :style="scrollHeight"
      @scroll="handleScroll"
    >
      <!-- <img class="img" v-for="src in imgSrcList" :key="src" :src="src" :alt="src" /> -->
      <canvas
        v-for="page in numPages"
        :id="'the-canvas' + page"
        :key="page"
      ></canvas>
    </div>

    <div v-if="imgSrcList.length !== 0" class="operation-box">
      <div class="operation">
        <div class="page-num-info">
          <span>{{ currentNum }}</span> /
          <span v-if="!inpDisabled">{{ numPages }}</span>
          <van-loading
            style="margin-left: 3px; margin-top: 3px"
            v-else
            size="14"
            type="spinner"
          />
        </div>
        <div class="jump-box" v-if="!inpDisabled">
          <div class="inp-box"></div>
        </div>
        <div v-else class="tips">文件加载中...</div>
        <div @click="handleBeforePage" class="home">
          <el-icon><ArrowLeftBold /></el-icon> 上一页 
        </div>
        <div @click="handleNextPage" class="home">
          下一页 <el-icon><ArrowRightBold /></el-icon>
        </div>
        <div @click="goToPage(1)" class="home" name="wap-home" size="20">
          首页
        </div>
      </div>
    </div>
    <SendEmail v-model:show="isShow" :pdfFileUrl="url" />
  </div>
</template>

<style scoped lang="scss">
@import url("./css.scss");

.overflow-y-scroll {
    background: #f2f3f5;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .canvas-div{
      display: flex;
      justify-content: center;
      padding-bottom: 4px;
      >canvas{
        border-radius: 2px;
        box-shadow: 0 -1px 8px 0 rgba(0,0,0,0.06);
      }
  }
}
</style>
